import { Store } from 'iflux2';
import { message } from 'antd'

import IntegralSetting from './actor/integral-setting';
import { getIntegralSetting, saveIntegralSetting } from './webApi';

export default class AppStore extends Store {
  bindActor() {
    return [
      new IntegralSetting
    ]
  }

  init = async () => {
    const { data } = await getIntegralSetting();
    this.dispatch('setting-init', data)
  }
  onSetting = (data) => {
    this.dispatch('handle-setting', data);
  }
  onRuleUpdate = (newRecord) => {
    this.dispatch('rule-update', newRecord);
  }
  onSettingUpdate = (newRecord) => {
    this.dispatch('setting-update', newRecord);
  }
  onSave = async (formValues) => {
    let {obtainTradePay, rewardRules, userLevels, ...others } = this.state().toJS();
    obtainTradePay.obtainVal = formValues.tradePay;
    rewardRules.push(obtainTradePay);
    var params = {
      isOpenSetting: formValues.isOpenSetting ? 1 : 0,//积分开启设置 0表示不启用，1表示启用
      grpIntegral: formValues.grpIntegral ? 1 : 0,//货到付款是否使用积分  0表示不使用，1表示使用
      orderObtainType: formValues.orderObtainType,//交易获得积分类型: 2按购买商品的固定积分 1按成交订单的金额比例 3混合模式
      ruleDescription: formValues.ruleDescription,//积分规则说明
      obtainSettingJson: JSON.stringify(rewardRules),//积分获取设置json详情
    }
    try{
        const { err } = await saveIntegralSetting(params);
        if (!err) {
          message.success('保存成功');
            const { data } = await getIntegralSetting();
            this.dispatch('setting-init', data)
        }
    }catch(err){
       message.error(err.message);
      return Promise.reject(err);
    }
  }
}